package com.alien.admin.context.task.handle.impl;

import com.alien.admin.context.task.handle.DeployJobHandler;
import com.alien.admin.context.task.TaskQueue;
import com.alien.admin.modules.deploy.domain.DeployRec;

import com.alien.admin.modules.deploy.service.DeployRecService;
import com.alien.admin.modules.deploy.service.DeployService;

import com.alien.admin.utils.DeployConstant;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author: zsy
 * @Date: 2021/10/28 11:22
 */
@Slf4j
@Data
@Component
public class JenkinsBuildImgJobHandler implements DeployJobHandler {
    @Autowired
    private DeployService deployService;
    @Autowired
    private DeployRecService deployRecService;
    @Autowired
    private TaskQueue taskQueue;

    @Override
    public void process(DeployRec deployRec) {
        // 进入部署
        try {
            DeployRec imageDeployRec = deployService.buildImage(deployRec.getId());

            // 任务中途被取消检验
            if(taskQueue.isCancelTask(deployRec.getId())) {
                return;
            }

            if(!DeployConstant.DEPLOY_STATUS_FAILED.equals(imageDeployRec.getDeployStatus())) {
                // 部署后，进入jenkins job状态监测
                imageDeployRec.setStage(DeployConstant.DEPLOY_STAGE_BUILD_IMAGE_CHECK);
                imageDeployRec.setDeployStatus(DeployConstant.DEPLOY_STATUS_NONE);
                deployRecService.update(imageDeployRec);

                taskQueue.putTaskToQueue(imageDeployRec.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            deployRec.setDeployStatus(DeployConstant.DEPLOY_STATUS_FAILED);
            deployRecService.update(deployRec);
        }
    }
}
